package anatex.semantics;

import java.util.ArrayList;
import java.util.List;

import anatex.domain.Category;
import anatex.domain.CustomLocale;
import anatex.domain.Document;
import anatex.domain.DocumentCategory;
import anatex.domain.Keyword;
import anatex.domain.KeywordDocument;

public class RelatedCategoriesFinder {

	public void findAndLog (Document document) {
		Wikipedia sw = new Wikipedia();
		
		//find related keywords
		try {
			List<KeywordDocument> relatedKeywords = KeywordDocument.findKeywordDocumentsByDocument(document).getResultList();
			
			for (KeywordDocument kd : relatedKeywords) {
				Keyword kwd = kd.getKeyword();
				ArrayList<Object[]> rc = sw.getRelatedCategories(kwd);
				StringBuffer b = new StringBuffer();
				
				for (Object[] s : rc) {
					b.append((String)s[0]);
					b.append("<br>");
					
					//try to find existing category
					String catName = (String)s[0];
					catName = catName.split(":")[1];
					Integer catWeight = (Integer)s[1];
					CustomLocale catLoc = (CustomLocale)s[2];
					Category cat;
					
					try {
						cat = Category.findCategorysByNameAndLocale(catName, catLoc).getSingleResult();
					} catch (Exception ex) {
						cat = new Category();
						cat.setName(catName);
						cat.setLocale(catLoc);
						
						cat.persist();
					}
					
					//try to find existing document location relation
					DocumentCategory dc;
					
					try {
						dc = DocumentCategory.findDocumentCategorysByDocumentAndCategory(kd.getDocument(), cat).getSingleResult();
						
						dc.setWeight(dc.getWeight() + catWeight);
						
						dc.merge();
					} catch (Exception ex) {
						//new document-category relation -s insert
						
						dc = new DocumentCategory();
						dc.setDocument(kd.getDocument());
						dc.setCategory(cat);
						dc.setWeight(catWeight);
						
						dc.persist();
					}
				}
			}
			
		} catch (Exception ex) {
			ex.printStackTrace(System.out);
		}
	}
	
}
